<template>
  <el-container
    style="height: 100vh; font-family: 'Segoe UI', sans-serif; background-color: #f5f7fa"
  >
    <!-- 左侧导航 -->
    <el-aside
      width="240px"
      style="background-color: #ffffff; border-right: 1px solid #e6e6e6; padding: 20px"
    >
      <h3 style="font-size: 18px; margin-bottom: 30px; color: #333; font-weight: 600">功能模块</h3>
      <el-menu
        default-active="text2image"
        :router="false"
        @select="handleMenuSelect"
        background-color="#ffffff"
        text-color="#333"
        active-text-color="#409EFF"
        style="border-right: none"
      >
        <el-menu-item index="text2image">
          <i class="el-icon-document-add" style="margin-right: 10px"></i>
          <span>AI文生图</span>
        </el-menu-item>
        <el-menu-item index="expandImage">
          <i class="el-icon-zoom-in" style="margin-right: 10px"></i>
          <span>AI扩图</span>
        </el-menu-item>
        <el-menu-item index="editImage">
          <i class="el-icon-edit" style="margin-right: 10px"></i>
          <span>AI图像编辑</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容 -->
    <el-main style="padding: 40px; background-color: #ffffff; overflow-y: auto">
      <!-- AI文生图模块 -->
      <div v-if="activeTab === 'text2image'">
        <h2 style="font-size: 24px; margin-bottom: 20px">🎨 AI文生图</h2>

        <el-row :gutter="30">
          <!-- 指令区 -->
          <el-col :span="8">
            <el-form :model="text2ImageForm" label-width="130px" label-position="top">
              <el-form-item label="文字描述">
                <el-input
                  v-model="text2ImageForm.prompt"
                  type="textarea"
                  :rows="4"
                  placeholder="输入图片描述，例如：一只飞翔的金色凤凰"
                />
              </el-form-item>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="图片尺寸">
                    <el-select v-model="text2ImageForm.size" placeholder="请选择图片尺寸">
                      <el-option label="256x256" value="256*256"></el-option>
                      <el-option label="512x512" value="512*512"></el-option>
                      <el-option label="1024x1024" value="1024*1024"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生成数量">
                    <el-input-number
                      v-model="text2ImageForm.n"
                      :min="1"
                      :max="10"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-button
                type="primary"
                @click="createTextToImageTask"
                style="width: 100%; margin-top: 15px; font-size: 16px; padding: 12px 0"
                :loading="loading"
              >
                🚀 生成图片
              </el-button>
            </el-form>
          </el-col>

          <!-- 图片展示区 -->
          <el-col :span="16">
            <div style="margin-top: 0">
              <h4
                style="margin-bottom: 15px; font-weight: 600"
                v-if="generatedImages.length || loading"
              >
                🖼️ 生成结果：
              </h4>
              <div class="image-grid">
                <!-- 骨架屏组件 -->
                <el-skeleton :loading="loading" animated :count="text2ImageForm.n" :throttle="300">
                  <!-- 自定义骨架模板 -->
                  <template #template>
                    <div
                      class="image-card"
                      v-for="(_, index) in text2ImageForm.n"
                      :key="`skeleton-${index}`"
                    >
                      <el-skeleton-item
                        variant="image"
                        style="width: 100%; height: 200px; border-radius: 4px"
                      />
                      <div style="margin-top: 10px; width: 100px; height: 28px">
                        <el-skeleton-item variant="text" />
                      </div>
                    </div>
                  </template>

                  <!-- 真实内容 -->
                  <template #default>
                    <div class="image-card" v-for="(img, index) in generatedImages" :key="index">
                      <el-image :src="img.url" alt="生成图片" fit="cover" lazy />
                      <el-button
                        type="text"
                        @click="downloadImage(img.url)"
                        style="margin-top: 10px"
                      >
                        <i class="el-icon-download" style="margin-right: 5px"></i> 下载图片
                      </el-button>
                    </div>
                  </template>
                </el-skeleton>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- AI扩图模块 -->
      <div v-if="activeTab === 'expandImage'">
        <h2 style="font-size: 24px; margin-bottom: 20px">🔍 AI扩图</h2>
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form label-width="130px" label-position="top">
              <el-form-item label="上传图片" class="upload-form-item">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleExpandImageUpload"
                  :show-file-list="false"
                  :before-upload="beforeImageUpload"
                >
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      justify-content: center;
                      height: 100%;
                    "
                  >
                    <i class="el-icon-plus" style="font-size: 24px; margin-bottom: 8px"></i>
                    <span>上传图片</span>
                  </div>
                </el-upload>
                <div style="margin-left: 20px">
                  <h4 style="margin-bottom: 15px; font-weight: 600">🖼️ 上传图片预览：</h4>
                  <div class="image-card" v-if="expandImagePreview">
                    <el-image :src="expandImagePreview" alt="上传的图片" fit="cover" lazy />
                    <el-progress
                      v-if="expandImageUploading"
                      :percentage="expandUploadProgress"
                      stroke-width="2"
                      style="width: 80%; margin-top: 10px"
                    ></el-progress>
                  </div>
                  <div
                    v-else
                    style="
                      color: #999;
                      text-align: center;
                      padding: 40px;
                      border: 2px dashed #e4e4e4;
                      border-radius: 12px;
                    "
                  >
                    尚未上传图片
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="文字描述">
                <el-input
                  v-model="expandInstruction"
                  type="textarea"
                  :rows="4"
                  placeholder="输入扩图描述，例如：在天空中的金色凤凰"
                />
              </el-form-item>
              <el-button
                type="primary"
                @click="expandImage"
                style="width: 100%; margin-top: 15px; font-size: 16px; padding: 12px 0"
                :loading="loading || expandImageUploading"
                :disabled="!expandImageUrl"
              >
                🖼️ 开始扩图
              </el-button>
            </el-form>
          </el-col>
          <el-col :span="16">
            <div style="margin-top: 30px">
              <h4
                style="margin-bottom: 15px; font-weight: 600"
                v-if="expandedImage.length || loading"
              >
                🔍 扩图结果：
              </h4>
              <div class="image-grid">
                <!-- 骨架屏组件 -->
                <el-skeleton :loading="loading" animated :count="1" :throttle="300">
                  <!-- 自定义骨架模板 -->
                  <template #template>
                    <div class="image-card">
                      <el-skeleton-item
                        variant="image"
                        style="width: 100%; height: 200px; border-radius: 4px"
                      />
                      <div style="margin-top: 10px; width: 100px; height: 28px">
                        <el-skeleton-item variant="text" />
                      </div>
                    </div>
                  </template>

                  <!-- 真实内容 -->
                  <template #default>
                    <div class="image-card" v-for="(img, index) in expandedImage" :key="index">
                      <el-image :src="img.url" alt="扩图结果" fit="cover" lazy />
                      <el-button
                        type="text"
                        @click="downloadImage(img.url)"
                        style="margin-top: 10px"
                      >
                        <i class="el-icon-download" style="margin-right: 5px"></i> 下载图片
                      </el-button>
                    </div>
                  </template>
                </el-skeleton>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- AI图像编辑模块 -->
      <div v-if="activeTab === 'editImage'">
        <h2 style="font-size: 24px; margin-bottom: 20px">✏️ AI图像编辑</h2>
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form label-width="130px" label-position="top">
              <el-form-item label="上传图片" class="upload-form-item">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleEditImageUpload"
                  :show-file-list="false"
                  :before-upload="beforeImageUpload"
                >
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      justify-content: center;
                      height: 100%;
                    "
                  >
                    <i class="el-icon-plus" style="font-size: 24px; margin-bottom: 8px"></i>
                    <span>上传图片</span>
                  </div>
                </el-upload>
                <div style="margin-left: 20px">
                  <h4 style="margin-bottom: 15px; font-weight: 600">🖼️ 上传图片预览：</h4>
                  <div class="image-card" v-if="editImagePreview">
                    <el-image :src="editImagePreview" alt="上传的图片" fit="cover" lazy />
                    <el-progress
                      v-if="editImageUploading"
                      :percentage="editUploadProgress"
                      stroke-width="2"
                      style="width: 80%; margin-top: 10px"
                    ></el-progress>
                  </div>
                  <div
                    v-else
                    style="
                      color: #999;
                      text-align: center;
                      padding: 40px;
                      border: 2px dashed #e4e4e4;
                      border-radius: 12px;
                    "
                  >
                    尚未上传图片
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="编辑指令">
                <el-input
                  v-model="editInstruction"
                  type="textarea"
                  :rows="4"
                  placeholder="如：去除水印、风格迁移为梵高画风、修复破损区域"
                />
              </el-form-item>
              <el-button
                type="primary"
                @click="editImage"
                style="width: 100%; margin-top: 15px; font-size: 16px; padding: 12px 0"
                :loading="loading || editImageUploading"
                :disabled="!editImageUrl || !editInstruction.trim()"
              >
                🎨 开始编辑
              </el-button>
            </el-form>
          </el-col>
          <el-col :span="16">
            <div style="margin-top: 30px">
              <h4
                style="margin-bottom: 15px; font-weight: 600"
                v-if="editedImage.length || loading"
              >
                🔍 编辑结果：
              </h4>
              <div class="image-grid">
                <!-- 骨架屏组件 -->
                <el-skeleton :loading="loading" animated :count="1" :throttle="300">
                  <!-- 自定义骨架模板 -->
                  <template #template>
                    <div class="image-card">
                      <el-skeleton-item
                        variant="image"
                        style="width: 100%; height: 200px; border-radius: 4px"
                      />
                      <div style="margin-top: 10px; width: 100px; height: 28px">
                        <el-skeleton-item variant="text" />
                      </div>
                    </div>
                  </template>

                  <!-- 真实内容 -->
                  <template #default>
                    <div class="image-card" v-for="(img, index) in editedImage" :key="index">
                      <el-image :src="img.url" alt="编辑结果" fit="cover" lazy />
                      <el-button
                        type="text"
                        @click="downloadImage(img.url)"
                        style="margin-top: 10px"
                      >
                        <i class="el-icon-download" style="margin-right: 5px"></i> 下载图片
                      </el-button>
                    </div>
                  </template>
                </el-skeleton>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import {
  getAITaskResultAPI,
  createTextToImageTaskAPI,
  createAIPictureEditPersonTaskAPI,
  uploadPictureToAliyunAPI,
} from '@/api/pictureAPI'
import { AIEditMode } from '@/types/AIEditMode'
import { ElMessage } from 'element-plus'

// 基础状态管理
const activeTab = ref('text2image')
const taskId = ref(null)
const timer = ref(null)
const loading = ref(false)

// 文生图模块
const text2ImageForm = ref({
  prompt: '',
  size: '1024*1024',
  n: 1,
})
const generatedImages = ref([])

// 扩图模块
const expandImageFile = ref(null)
const expandImageUrl = ref(null)
const expandImagePreview = ref(null)
const expandImageUploading = ref(false)
const expandUploadProgress = ref(0)
const expandedImage = ref([]) // 修改为数组，支持多图
const expandInstruction = ref('')

// 图像编辑模块
const editImageFile = ref(null)
const editImageUrl = ref(null)
const editImagePreview = ref(null)
const editImageUploading = ref(false)
const editUploadProgress = ref(0)
const editInstruction = ref('')
const editedImage = ref([]) // 修改为数组，支持多图

// 菜单切换
function handleMenuSelect(index) {
  activeTab.value = index
}

// 文生图任务处理
async function createTextToImageTask() {
  if (!text2ImageForm.value.prompt.trim()) {
    ElMessage.warning('请输入生成图片的提示词')
    return
  }
  if (taskId.value) {
    ElMessage.info('任务已存在，请勿重复创建')
    return
  }

  loading.value = true
  try {
    const res = await createTextToImageTaskAPI(text2ImageForm.value)
    taskId.value = res.data
    ElMessage.info('创建任务成功，请耐心等待生成结果...')
    getTextToImageTaskResult()
  } catch (error) {
    ElMessage.error('创建任务失败: ' + (error.message || '未知错误'))
    loading.value = false
  }
}

// 任务轮询通用函数
const taskPolling = (task, params, callback, errorCallback, timeout = 3000) => {
  timer.value = setInterval(async () => {
    try {
      const res = await task(params)
      const taskResult = res.data.output

      if (taskResult.taskStatus === 'SUCCEEDED') {
        ElMessage.success('生成成功')
        taskId.value = null
        clearInterval(timer.value)
        callback(taskResult)
        loading.value = false
      } else if (taskResult.taskStatus === 'FAILED') {
        ElMessage.error('生成失败: ' + taskResult.message)
        taskId.value = null
        clearInterval(timer.value)
        errorCallback()
        loading.value = false
      }
    } catch (error) {
      ElMessage.error('获取任务结果失败: ' + (error.message || '未知错误'))
      clearInterval(timer.value)
      loading.value = false
    }
  }, timeout)
}

// 获取文生图任务结果
async function getTextToImageTaskResult() {
  if (!taskId.value) {
    ElMessage.info('任务不存在，请重新创建')
    return
  }

  loading.value = true
  taskPolling(
    getAITaskResultAPI,
    taskId.value,
    (taskResult) => {
      generatedImages.value = taskResult.results
      loading.value = false
    },
    () => {
      ElMessage.info('任务失败')
      loading.value = false
    },
  )
}

// 图片上传前校验
function beforeImageUpload(file) {
  const isJpgOrPng =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG、PNG或WEBP格式的图片!')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }

  return true
}

// 处理扩图图片上传
function handleExpandImageUpload(file) {
  // 重置之前的上传状态
  if (expandImagePreview.value) {
    URL.revokeObjectURL(expandImagePreview.value)
  }

  // 设置新的上传状态
  expandImageUploading.value = true
  expandUploadProgress.value = 0
  expandImageFile.value = file.raw
  expandImagePreview.value = URL.createObjectURL(file.raw)
  expandedImage.value = [] // 清空之前的结果

  // 上传到阿里云
  uploadImageToAliyun(
    file.raw,
    (url) => {
      expandImageUrl.value = url
      expandImageUploading.value = false
    },
    (progress) => {
      expandUploadProgress.value = progress
    },
    () => {
      expandImageUploading.value = false
      expandImagePreview.value = null
      expandImageUrl.value = null
    },
  )
}

// 处理编辑图片上传
function handleEditImageUpload(file) {
  // 重置之前的上传状态
  if (editImagePreview.value) {
    URL.revokeObjectURL(editImagePreview.value)
  }

  // 设置新的上传状态
  editImageUploading.value = true
  editUploadProgress.value = 0
  editImageFile.value = file.raw
  editImagePreview.value = URL.createObjectURL(file.raw)
  editedImage.value = [] // 清空之前的结果

  // 上传到阿里云
  uploadImageToAliyun(
    file.raw,
    (url) => {
      editImageUrl.value = url
      editImageUploading.value = false
    },
    (progress) => {
      editUploadProgress.value = progress
    },
    () => {
      editImageUploading.value = false
      editImagePreview.value = null
      editImageUrl.value = null
    },
  )
}

// 上传图片到阿里云
async function uploadImageToAliyun(file, successCallback, progressCallback, errorCallback) {
  try {
    const res = await uploadPictureToAliyunAPI(file, progressCallback)
    if (res.data) {
      ElMessage.success('图片上传成功')
      successCallback(res.data)
    } else {
      ElMessage.error('图片上传失败')
      if (errorCallback) errorCallback()
    }
  } catch (error) {
    ElMessage.error('图片上传失败: ' + (error.message || '未知错误'))
    console.error('上传失败', error)
    if (errorCallback) errorCallback()
  }
}

// 创建图片编辑任务通用函数
async function createAIPictureEditPersonTask(params, fun) {
  try {
    const res = await createAIPictureEditPersonTaskAPI(params)
    taskId.value = res.data
    ElMessage.info('任务创建成功，请耐心等待生成结果...')
    fun()
  } catch (error) {
    ElMessage.error('创建任务失败: ' + (error.message || '未知错误'))
    loading.value = false
  }
}

// 扩图操作
async function expandImage() {
  if (!expandImageFile.value) {
    ElMessage.warning('请先上传一张图片')
    return
  }

  if (!expandImageUrl.value) {
    ElMessage.warning('图片正在上传，请稍后重试')
    return
  }

  if (!expandInstruction.value.trim()) {
    ElMessage.warning('请输入扩图指令')
    return
  }

  loading.value = true
  createAIPictureEditPersonTask(
    {
      function: AIEditMode.EXPAND.functionName,
      baseImageUrl: expandImageUrl.value,
      prompt: expandInstruction.value.trim(),
    },
    getAIPictureExpandTaskResult,
  )
}

// 获取扩图结果
async function getAIPictureExpandTaskResult() {
  if (!taskId.value) {
    ElMessage.warning('任务不存在，请重新创建')
    return
  }

  loading.value = true
  taskPolling(
    getAITaskResultAPI,
    taskId.value,
    (taskResult) => {
      expandedImage.value = taskResult.results || []
      loading.value = false
    },
    () => {
      ElMessage.info('任务失败')
      loading.value = false
    },
  )
}

// 图像编辑操作
async function editImage() {
  if (!editImageFile.value) {
    ElMessage.warning('请先上传一张图片')
    return
  }

  if (!editImageUrl.value) {
    ElMessage.warning('图片正在上传，请稍后重试')
    return
  }

  if (!editInstruction.value.trim()) {
    ElMessage.warning('请输入编辑指令')
    return
  }

  loading.value = true
  await createAIPictureEditPersonTask(
    {
      function: AIEditMode.DESCRIPTION_EDIT.functionName,
      baseImageUrl: editImageUrl.value,
      prompt: editInstruction.value.trim(),
    },
    getAIPictureEditPersonTaskResult,
  )
}

// 获取图像编辑结果
async function getAIPictureEditPersonTaskResult() {
  if (!taskId.value) {
    ElMessage.warning('任务不存在，请重新创建')
    return
  }

  loading.value = true
  taskPolling(
    getAITaskResultAPI,
    taskId.value,
    (taskResult) => {
      editedImage.value = taskResult.results || []
      loading.value = false
    },
    () => {
      ElMessage.info('任务失败')
      loading.value = false
    },
  )
}

// 下载图片
function downloadImage(url) {
  const a = document.createElement('a')
  a.href = url
  a.download = `image-${Date.now()}.png`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 组件卸载时清理资源
onUnmounted(() => {
  // 清除定时器
  if (timer.value) {
    clearInterval(timer.value)
  }

  // 释放URL对象
  if (expandImagePreview.value) {
    URL.revokeObjectURL(expandImagePreview.value)
  }
  if (editImagePreview.value) {
    URL.revokeObjectURL(editImagePreview.value)
  }
})
</script>

<style scoped>
.image-card {
  width: 240px; /* 固定最小宽度，确保卡片大小一致 */
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-card .el-image {
  width: 100%;
  height: 200px; /* 固定高度，确保骨架屏和图片高度一致 */
  display: block;
  border-radius: 4px;
}

.image-card:hover {
  transform: translateY(-4px);
}

.el-menu-item.is-active {
  background-color: #ecf5ff !important;
  font-weight: bold;
  color: #409eff !important;
}

.el-button {
  font-weight: 500;
  transition: all 0.2s ease;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

@media (max-width: 992px) {
  .el-row {
    flex-direction: column;
  }
  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }

  .image-card {
    min-width: 200px;
  }
}
</style>
